import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/auth/Login.vue'
import AdminLayout from '../layouts/AdminLayout.vue'
import Home from '../views/home/Home.vue'

// 添加类型声明以解决 import.meta 类型错误
interface ImportMeta {
  env: Record<string, any>
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
    },
    {
      path: '/',
      component: AdminLayout,
      children: [
        {
          path: '/home',
          name: 'home',
          component: Home,
        },
        {
          path: '/settings/profile',
          name: 'settings-profile',
          component: () => import('../views/settings/SettingsProfile.vue'),
        }
      ],
    },
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查是否已登录
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'
  
  // 如果访问的不是登录页且未登录，则跳转到登录页
  if (to.name !== 'login' && !isAuthenticated) {
    next({ name: 'login' })
  } else {
    next()
  }
})

export default router
